import i18n from '@/i18n/i18n'
import {
  adminSystemIndexAPI,
  PcCustomKeys,
  adminConfigQueryCustomSettingAPI
} from '@/api/admin/config'

import { crmSettingConfigDataAPI } from '@/api/admin/crm'
import { adminConfigsetIndexAPI } from '@/api/admin/application'
import {
  adminUsersQueryLanguageListAPI,
  adminUsersQueryDeflautLanguageAPI
} from '@/api/user/personCenter'

import { adminUserQueryUserDeflautLanguageInfoAPI } from '@/api/admin/language.js'
import { adminAuthModuleListAPI } from '@/api/common'
import Lockr from 'lockr'
import merge from '@/utils/merge'
// import { getImageData } from '@/utils'
import { loadLanguageSync, setI18nLanguage } from '@/i18n/utils'
import { isArray, isObject } from '@/utils/types'

const DefaultSystemAlertProps = {
  title: '',
  type: 'warning',
  description: '',
  closable: true,
  center: false,
  closeText: '',
  showIcon: true,
  effect: 'light'
}

/** 记录 侧边索引 */
const lang = Lockr.get('lang')
const loadedLangs = []
if (lang) loadedLangs.push(lang)

const app = {
  state: {
    logo: '',
    name: '',
    lang: lang, // 当前语言
    langs: [], // 所有语言
    loadedLangs: loadedLangs, // i18n已载入语言 同 i18n.messages
    // 菜单颜色信息
    menuColorData: {},
    sidebar: {
      backgroundColor: '#fff',
      selectedBackground: '#EBECF0',
      hoverBackground: '#EBECF0',
      color: '#172B4D',
      selectedColor: '#172B4D',
      hoverColor: '#172B4D',
      collapse: Lockr.get('sideBarCollapse') || false
    },
    // CRM配置信息
    CRMConfig: {},
    // 图片缓存
    imageCache: {},
    // 活动咨询是否开启
    marketingEnable: false,
    // 导航栏系统提示
    systemAlertShow: false,
    systemAlertProps: DefaultSystemAlertProps,
    // 模块权限
    moduleAuth: null,
    // 当前账套的月份
    nowMounth: '',
    pendingMap: new Map(), // 取消请求token数组

    moduleData: [], // 各模块状态 包含 时间 次数等信息
    // 系统模块列表
		systemModuleList: []
  },

  mutations: {
    SET_NOWMOUNTH: (state, num) => {
      state.nowMounth = num
    },
    SET_COLLAPSE: (state, collapse) => {
      state.sidebar.collapse = collapse
      Lockr.set('sideBarCollapse', collapse)
    },
    SET_SIDEBAR: (state, options) => {
      state.sidebar = {
        ...state.sidebar,
        ...options
      }
    },
    SET_APPLOGO: (state, logo) => {
      state.logo = logo
    },
    SET_APPNAME: (state, name) => {
      state.name = name
    },
    SET_LANG: (state, lang) => {
      state.lang = lang
      // window.app.$i18n.locale = lang
      // localStorage.setItem('lang', lang)
      // moment.locale(lang || 'zh-CN')
      // window.location.reload()
    },
    SET_LANGS: (state, langs) => {
      state.langs = langs
    },
    SET_LOADEDLANGS: (state, loadedLangs) => {
      state.loadedLangs = loadedLangs
    },
    SET_CRMCONFIG: (state, config) => {
      state.CRMConfig = config
    },
    SET_IMAGECACHE: (state, value) => {
      state.imageCache = value
    },
    SET_MARKETINGENABLE: (state, value) => {
      state.marketingEnable = value
    },
    SET_SYSTEMALERTSHOW: (state, value) => {
      state.systemAlertShow = value
    },
    SET_SYSTEMALERTPROPS: (state, value) => {
      state.systemAlertProps = merge(
        { ...DefaultSystemAlertProps },
        value || {}
      )
    },
    SET_MODULEAUTH: (state, value) => {
      state.moduleAuth = value
    },
    // pendingMap
    Add_CANCEL_TOKEN({ pendingMap }, { url, cancel }) {
      if (!pendingMap.has(url)) {
        pendingMap.set(url, cancel)
      }
    },
    Remove_CANCEL_TOKEN({ pendingMap }, { url = '' }) {
      if (pendingMap.has(url)) {
        pendingMap.delete(url)
      }
    },
    CLEAR_CANCEL_TOKEN({ pendingMap }) {
      pendingMap.forEach((cancel) => {
        cancel(i18n.t('modules.app.776d45666cfc34049df083da026c0129'))
      })
      pendingMap.clear()
    },

    SET_MODULE_DATA(state, data) {
      state.moduleData = data
    },
    SET_MENU_COLOR_DATA(state, data) {
      state.menuColorData = data
    },
    SET_SYSTEM_MODULE_LIST(state, data) {
			state.systemModuleList = data
		},
  },

  actions: {
    // 登录
    SystemLogoAndName({ commit }) {
      return new Promise((resolve, reject) => {
        adminSystemIndexAPI()
          .then((response) => {
            const resData = response.data || {}
            commit('SET_APPNAME', resData.companyName)
            commit('SET_APPLOGO', resData.companyLogo)
            Lockr.set('systemLogo', resData.companyLogo)
            Lockr.set('systemName', resData.companyName)

          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    /**
     * 获取客户管理配置
     */
    CRMSettingConfig({ commit }) {
      return new Promise((resolve, reject) => {
        crmSettingConfigDataAPI()
          .then((response) => {
            commit('SET_CRMCONFIG', response.data)
            resolve(response)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    /**
     * 获取客户管理配置
     */
    GetMenuColorData({ commit }) {
      return new Promise((resolve, reject) => {
        adminConfigQueryCustomSettingAPI(PcCustomKeys.pcMenuStyle)
          .then((response) => {
            const resData = response.data
            if (isArray(resData) && resData.length > 0) {
              const config = resData[0] // 值规范是数组 所以默认放在第一个元素里
              if (isObject(config)) {
                commit('SET_MENU_COLOR_DATA', config)
              }
            } else {
              commit('SET_MENU_COLOR_DATA', {})
            }
            resolve(response)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // // 查询活动配置
    // QueryMarketing({
    //   commit,
    //   state
    // }) {
    //   return new Promise((resolve, reject) => {
    //     configQueryMarketingAPI().then(res => {
    //       state.marketingEnable = res.data == 1
    //       resolve(res)
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },
    // 获取当前语言和默认语言info  不带 语言 包
    QueryLangInfo({ dispatch }) {
      return new Promise((resolve, reject) => {
        adminUserQueryUserDeflautLanguageInfoAPI({ languagePackType: 1 })
          .then((res) => {
            const localLanguageUpdateTime =
              Lockr.get('languageUpdateTime') || ''
            const { languagePackName, updateTime } = res.data
            const lang = Lockr.get('lang')
            if (
              localLanguageUpdateTime !== updateTime ||
              lang !== languagePackName
            ) {
              // Lockr.set('languageUpdateTime', updateTime)
              dispatch('GetDefaultLang').then((_) => {
                window.location.reload()
              })
            } else {
              const languagePack = JSON.parse(
                window.localStorage.getItem('localeMessages')
              )
              loadLanguageSync(lang, languagePack)
            }
            resolve()
          })
          .catch((e) => {
            reject()
          })
      })
    },
    // 获取当前语言和默认语言
    QueryLangs({ commit }) {
      return new Promise((resolve, reject) => {
        adminUsersQueryLanguageListAPI({ pageType: 0 })
          .then((res) => {
            const langs = res.data.list || []
            commit('SET_LANGS', langs)
            // const selectLang = langs.find(item => item.defaultLanguage === 1)

            // commit('SET_LANG', selectLang ? selectLang.languagePackName : 'zh-CN')
            resolve && resolve(res)
          })
          .catch((error) => {
            reject && reject(error)
          })
      })
    },

    // 获取默认语言内容
    GetDefaultLang({ commit, state }) {
      return new Promise((resolve, reject) => {
        adminUsersQueryDeflautLanguageAPI()
          .then((res) => {
            const resData = res.data
            if (resData && resData.languagePackContext) {
              // 保存当前语言
              const lang = resData.languagePackName
              commit('SET_LANG', lang)
              window.localStorage.setItem(
                'lang',
                resData.languagePackName || ''
              )
              window.localStorage.setItem(
                'localeMessages',
                resData.languagePackContext
              )
              Lockr.set('languageUpdateTime', resData.updateTime)
              resolve && resolve(resData)
            } else {
              setI18nLanguage('zh-CN')
              reject && reject()
            }
          })
          .catch(() => {
            setI18nLanguage('zh-CN')
            reject && reject()
          })
      })
    },

    // 查询模块权限
    QueryModules({
      commit,
      state,
      getters
    }) {
      return new Promise((resolve, reject) => {
        adminConfigsetIndexAPI().then(res => {
          let resData = res.data || []
          // status 状态 1:启用 0:停用 2:试用中 3:已过期,可用值:0,1,2,3
          const auth = {}
          // 企业微信工作天
          if (getters.userInfo && getters.userInfo.loginType == 3) {
            const validModules = ['taskExamine', 'log', 'book', 'crm']
            resData = resData.filter(item => validModules.includes(item.module))
          }
          resData.forEach(item => {
            auth[item.module] = item.status === 1 || item.status === 2
          })
          commit('SET_MODULEAUTH', auth)
          commit('SET_MODULE_DATA', resData)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 菜单模块权限列表
		QuerySystemModuleList({ commit, state, getters }) {
			return new Promise((resolve, reject) => {
				adminAuthModuleListAPI()
					.then(res => {
						if (res.data && res.data.length > 0) {
							let resData = res.data.filter(item => Boolean(item))
							commit("SET_SYSTEM_MODULE_LIST", resData)
							resolve(res)
						} else {
							commit("SET_SYSTEM_MODULE_LIST", [])
              reject(res)
            }
					})
					.catch(error => {
						reject(error)
					})
			})
		}
  },

  getters: {
    lang: (state) => state.lang,
    langs: (state) => state.langs,
    app: (state) => state,
    logo: (state) => {
      if (state.logo) {
        return state.logo
      }
      return require('@/assets/img/logo.jpg')
    },
    name: (state) => {
      if (state.name) {
        return state.name
      }
      return window.WKConfig.companyName
    },
    nowMounth: (state) => state.nowMounth,
    moduleData: (state) => state.moduleData,

    collapse: (state) => state.sidebar.collapse,
    sidebar: (state) => state.sidebar,
    menuColorData: (state) => state.menuColorData,
    systemAlertShow: (state) => state.systemAlertShow,
    systemAlertProps: (state) => state.systemAlertProps,
    moduleAuth: (state) => state.moduleAuth,

    // 配置信息
    CRMConfig: (state) => state.CRMConfig,
    imageCache: (state) => state.imageCache,
    // 模块权限列表
		systemModuleList: state => state.systemModuleList,
  }
}

export default app
